package com.xjscrm.console.chat.core.impl.conversation;

import cn.hutool.core.util.IdUtil;
import com.uzai.mobile.collect.api.MicaTopics;
import com.uzai.mobile.collect.api.dto.MicaTriggerDto;
import com.uzai.mobile.collect.api.dto.trigger.group.MicaTriggerGroupAddMsg;
import com.uzai.mobile.collect.api.enums.MicaTriggerType;
import com.xjscrm.common.entity.WwDevice;
import com.xjscrm.common.enums.ChatConversationTypeEnum;
import com.xjscrm.common.exception.BusinessException;
import com.xjscrm.console.chat.core.ChatBaseMsgHandler;
import com.xjscrm.console.chat.enums.ChatMsgType;
import com.xjscrm.console.chat.frame.recv.RPullNewGroupConversationMsg;
import com.xjscrm.console.chat.frame.send.SResultMsg;
import com.xjscrm.console.entity.ChatTalkSession;
import com.xjscrm.console.mq.producer.SendMsgProducer;
import com.xjscrm.console.service.customer.chat.ChatTalkSessionService;
import com.xjscrm.console.service.customer.chat.ChatTalkSessionStaffRelService;
import com.xjscrm.console.service.customer.wwDevice.WwDeviceService;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * @author mingyang.chen create in 2024/3/17 09:42
 */
@Component
@Slf4j
public class ChatPullNewGroupConversationMsgHandler extends ChatBaseMsgHandler<RPullNewGroupConversationMsg> {

    @Autowired
    private SendMsgProducer sendMsgProducer;

    @Autowired
    private WwDeviceService wwDeviceService;

    @Autowired
    private ChatTalkSessionService chatTalkSessionService;
    @Autowired
    private ChatTalkSessionStaffRelService chatTalkSessionStaffRelService;

    @Override
    public Class<RPullNewGroupConversationMsg> msgClass() {
        return RPullNewGroupConversationMsg.class;
    }

    @Override
    public boolean checkMsg(RPullNewGroupConversationMsg baseMsg) {
        return super.checkMsg(baseMsg) || !ObjectUtils.isNotEmpty(baseMsg.getWxIds()) || !StringUtils.isNotBlank(baseMsg.getConversationName()) || !Objects.nonNull(baseMsg.getDeviceUniqueId());
    }

    @Override
    public SResultMsg doHandle(RPullNewGroupConversationMsg content, ChannelHandlerContext ctx) {

        Long merId = content.getMerId();
        Long staffId = content.getStaffId();
        Long deviceUniqueId = content.getDeviceUniqueId();

        WwDevice device = wwDeviceService.getById(merId, deviceUniqueId);
        if (Objects.isNull(device)) {
            throw new BusinessException("群聊创建失败: 设备未找到");
        }
        if (chatTalkSessionService.checkConversationName(merId, deviceUniqueId, content.getConversationName())) {
            throw new BusinessException("群聊创建失败: 群名重复");
        }
        ChatTalkSession talkSession = new ChatTalkSession();
        talkSession.setId(IdUtil.getSnowflakeNextId());
        talkSession.setMerId(merId);
        talkSession.setDeviceUniqueId(deviceUniqueId);
        talkSession.setDeviceId(device.getDeviceId());
        talkSession.setDeviceType(device.getDeviceType());
        talkSession.setConversationName(content.getConversationName());
        talkSession.setConversationId(talkSession.getId().toString());
        talkSession.setType(ChatConversationTypeEnum.group_conversation.getCode());

        talkSession.setCreateTime((int) (System.currentTimeMillis() / 1000L));
        talkSession.setUpdateTime((int) (System.currentTimeMillis() / 1000L));

        chatTalkSessionService.add(talkSession);
        // 添加关联关系
        chatTalkSessionStaffRelService.addIfAbsent(merId, talkSession, staffId);

        MicaTriggerGroupAddMsg micaTriggerGroupAddMsg = new MicaTriggerGroupAddMsg();
        micaTriggerGroupAddMsg.setMessageId(talkSession.getId());
        micaTriggerGroupAddMsg.setGroupName(content.getConversationName());
        micaTriggerGroupAddMsg.setWxIds(StringUtils.join(content.getWxIds(), ";"));

        MicaTriggerDto micaTriggerDto = MicaTriggerDto.newInstance(micaTriggerGroupAddMsg, MicaTriggerType.TRIGGER_GROUP_ADD, item -> {
            item.setReqId(talkSession.getId());
            item.setDeviceId(device.getDeviceId());
            item.setDeviceType(device.getDeviceType());
        });

        sendMsgProducer.pushMsg(micaTriggerDto, MicaTopics.WW_TRIGGER_TOPIC);

        return SResultMsg.success(content, "群聊创建中");
    }

    @Override
    public ChatMsgType msgType() {
        return ChatMsgType.r_pull_new_group_conversation;
    }
}
